<?php
class PosterModel extends Model{
	private $api;
	private $username;
	
	
	public function _initialize(){
	     	$this->api = new TS_API();
	}
	
	public function getPosterList($pid=null,$type=null,$uid = null,$private = null){
		isset($pid) && $map['pid'] = $pid;
		isset($type) && $map['type'] = $type;
        isset($private) && $map['private'] = $private;
        if(isset($this->username)){
        	$map['name'] = $this->username;
        	unset($map['uid']);
        	
        }
		if(is_array($uid)){
			$map['uid'] = array('in',$uid);
		}else{
			if(isset($uid)){
				$map['uid'] = $uid;
			}
				
		}
	   $result = $this->where($map)->order('cTime DESC')->field('id,pid,type,name,uid,content,title,deadline,private,conver,cTime')->findPage(20);
	   $result['data'] = $this->replace($result['data']);
	   return $result;
	}
	public function setUserName($name){
		$this->username = $name;
	}
	public function getPoster($id,$mid){
		$map['id'] = $id;
        $result = $this->where($map)->find();
        $posterSmallTypeDao = D('PosterSmallType');
        $posterTypeDao = D('PosterType');
        if(!$result) return false;
        if($mid !=$result['uid'] && $result['private'] == 1 && false == $this->api->friend_areFriends($mid,$result['uid'])) return false;
        $result['posterType'] = $posterTypeDao->getTypeName($result['pid']);
        $result['posterSmallType'] = $posterSmallTypeDao->getTypeName($result['type']);
        isset($result['conver']) && $result['cover'] = UPLOAD_URL.$result['conver'];
        $result['address'] = getAreaInfo($result['address_province'].','.$result['address_city']);
        return $result;
	}
	
	public function deletePoster($id,$mid){
		$poster = $this->where('id='.$id)->find();
		if(!$poster) return -2;
		if($poster['uid'] != $mid) return -1;
		
		$rs = $this->where('id='.$id)->delete();
		if($rs){
			$count = $this->where('uid ='.$poster['uid'])->count();
			$this->api->space_changeCount( 'poster',$count );
			return 1;
		}else{
			return 0;
		}
	}
	
    private function replace($data){
    	$result = $data;
    	$posterSmallTypeDao = D('PosterSmallType');
    	$posterTypeDao = D('PosterType');
    	$posterST = $posterSmallTypeDao->getPosterSmallTypeByIdArray();
    	$posterT = $posterTypeDao->getPosterTypeByIdArray();
        $posterType = D('PosterType');
    	foreach($result as &$value){
           $value['type'] = $posterST[$value['type']];
           $value['content'] = getBlogShort($value['content'],20);
           $value['posterType'] = $posterT[$value['pid']];
           $value['cover'] = UPLOAD_URL.$value['conver'];
    	}
    	return $result;
    }
}